package com.iraeta.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.iraeta.dao.CaizhigongyiDao;
import com.iraeta.dao.GongyiDao;
import com.iraeta.entity.Caizhigongyi;
import com.iraeta.entity.Gongyi;
import com.iraeta.service.GongYiService;
import com.iraeta.uitl.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class GongYiServiceImpl implements GongYiService {
    @Autowired
    GongyiDao gongyiDao;
    @Autowired
    CaizhigongyiDao caizhigongyiDao;

    @Override
    public void addGongyi(Gongyi gongyi) {
        gongyiDao.insert(gongyi);
    }

    @Override
    public void updateGongyi(Gongyi gongyi) {
        gongyiDao.updateByPrimaryKey(gongyi);
    }

    @Override
    public void deleteGongyi(Integer id) {
        gongyiDao.deleteByPrimaryKey(id);
    }

    @Override
    public Gongyi getGongyi(Integer id) {
        return gongyiDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Gongyi> listAllGongyi() {
        return gongyiDao.selectAll();
    }

    @Override
    public List<Gongyi> listGongyi(String gongyitype, String name) {
        return gongyiDao.selectByName(gongyitype, name);
    }

    @Override
    public List<Gongyi> listCaiZhiGongyi(String gongyitype, Integer caizhiid) {
        return gongyiDao.listCaiZhiGongyi(gongyitype, caizhiid);
    }

    @Transactional
    @Override
    public void saveCaiZhiGongyi(Integer caizhiid, String gongyitype, JSONArray gongYiJa) {
        List<Integer> gongyiList = new ArrayList<>();
        for(int i =0; i<gongYiJa.size(); i++){
            gongyiList.add(gongYiJa.getIntValue(i));
        }
        for (Integer gongyiId : gongyiList) {
            if(caizhigongyiDao.selectByCaiZhiGongYi(caizhiid, gongyiId) == null){
                Caizhigongyi caizhigongyi = new Caizhigongyi(caizhiid, gongyiId);
                caizhigongyiDao.insert(caizhigongyi);
            }
        }
        String gongyiIdStr = Util.parseListToString(gongyiList);
        caizhigongyiDao.deleteCaiZhiGongYiIdStr(caizhiid, gongyitype, gongyiIdStr);
    }
}
